//
//  WmcEditTeamMemberInfoVM.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/14.
//

import Foundation
import SVProgressHUD

class WmcEditTeamMemberInfoVM: WmcBaseVM {
    var teamMember: WmcTeamMemberModel?
    var teamAblum: WmcMediaTeamAlbumModel?

    /// 成员详情
    let teamMemberDetail: BehaviorRelay<WmcTeamMemberDetailModel?> = .init(value: nil)

    /// 获取成员详情
    /// - Returns: description
    func getMemberDetail() {
        guard let teamId = teamMember?.teamId,
              let memberId = teamMember?.memberId,
              let yupaoId = teamMember?.uid else { return }

        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.fetchMemberInfo(teamId: teamId, memberId: memberId, yupaoId: yupaoId).subscribe { [weak self] detail in
            guard let weakSelf = self else { return }
            weakSelf.teamMemberDetail.accept(detail)
            WmcHudManager.dismiss()
        } onError: { error in
            WmcHudManager.toast(error)
            WmcHudManager.dismiss()
        }.disposed(by: rx.disposeBag)
    }

    /// 删除团队成员
    /// - Parameters:
    ///   - teamId: 团队id
    ///   - memberId: 团队成员id
    /// - Returns: description
    func deleteMember(succeed: (() -> Void)?) {
        guard let teamId = teamMember?.teamId, let memberId = teamMember?.memberId else { return }
        SVProgressHUD.show()
        WmcMediaTeamManagerAPI.deleteMember(teamId: teamId, memberId: memberId).subscribe { _ in
            SVProgressHUD.dismiss()
            guard let succeed = succeed else {
                return
            }
            succeed()
        } onError: { error in
            SVProgressHUD.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }

    func updateUserAvatar(imgUrl: String, succeedBlock: (() -> Void)?) {
        WmcHudManager.loading()
        WmcMediaUserCenterAPI.updateAvatar(imageUrl: imgUrl).subscribe { res in
            WmcHudManager.toast(res.msg)
            WmcHudManager.dismiss()
            guard let succeedBlock = succeedBlock else {
                return
            }
            succeedBlock()
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }

    /// 上传头像
    func uploadUserAvatar(_ image: UIImage,
                          successBlock: @escaping YPBlock.OneParam<String>,
                          failureBlock: YPBlock.Empty? = nil) {
        guard let imageData = image.yp.jpegData else { return }
        var params: WmcUploadFileModel = .init()
        params.entryId = 555574
        params.type = 0
        params.format = "png"

        WmcUploadManager.uploadFile(data: imageData, params: params, progress: nil) { url in
            successBlock(url.url)
        } failure: { error in
            failureBlock?()
            WmcHudManager.toast(error)
        }
    }
}
